#!/usr/bin/bash


authselect check &> /dev/null && auCheck=0

if [[ $auCheck == "0" ]] ; then
    customProfile=$(authselect current | awk 'NR == 1 {print $3}' | grep custom/)
    currProfile=$(authselect current | awk 'NR == 1 {print $3}')
    createP="user-profile"

    # 判断是否已有用户自定义规则集，如有则跳过创建步骤，改为直接追加已有的规则集
    if [[ -z $customProfile ]]; then
        authselect create-profile $createP -b $currProfile
        authselect select custom/$createP
        authselect apply-changes
    fi
fi

[[ $auCheck == "0" ]] && customProfile=$(authselect current | awk 'NR == 1 {print $3}' | grep custom/) || customProfile=""
# 判断是否有自定义规则集，如没有或创建失败，则直接对最终文件(/etc/pam.d/password-auth,/etc/pam.d/system-auth)进行修改
for FN in system-auth; do
    [[ -n $customProfile ]] && PTF=/etc/authselect/$customProfile/$FN || PTF=/etc/pam.d/$FN
    [[ -z $(grep -E '^\s*password\s+requisite\s+pam_pwhistory.so.*$' $PTF) ]] && ln=$(grep -En -m1 '^\s*password\s+' $PTF | cut -d: -f1) && sed -i "${ln}i\password    requisite    pam_pwhistory.so " $PTF
    [[ -z $(grep -E '^\s*password\s+sufficient\s+pam_unix.so.*$' $PTF) ]] && ln=$(grep -En -m1 '^\s*password\s+' $PTF | cut -d: -f1) && sed -i "${ln}i\password    sufficient    pam_unix.so " $PTF

    rememberLN=$(grep -En '^\s*password\s+.*(pam_pwhistory.so|pam_unix.so)\s*.*' $PTF | grep -Pv "remember=" | cut -d: -f1)
    if [[ -n $rememberLN ]] ; then
        for l in $rememberLN; do sed -ri "${l}s/(^\s*password\s+)(\s+requisite\s+|\s+sufficient\s+)(\s+pam_pwhistory\.so\b\s*|\s+pam_unix\.so\b\s*)(.*)$/\1\2\3\4 remember=5 /" $PTF ; done
    elif [[ -n $(grep -E '^\s*password\s+(requisite|sufficient)\s+(pam_pwhistory.so|pam_unix.so)\s*.*remember=\S+\s*.*$' $PTF) ]] ;then
        sed -ri "/^\s*password\s+(requisite|sufficient)\s+(pam_pwhistory.so|pam_unix.so)/s/remember=\S+/remember=5/g" $PTF
    fi

done

[[ $auCheck == "0" ]] && authselect apply-changes &> /dev/null
